/*
 * @Author: 麦冬果果
 * @Date: 2021-09-03 09:58:44
 * @LastEditTime: 2021-09-11 09:07:58
 * @LastEditors: 麦冬果果
 * @Description:应用注册 采用定时器 执行一次
 * @FilePath: /svc/src/boot/register.go
 * 可以输入预定的版权声明、个性签名、空行等
 */
package boot

import (
	"fastapi/src/library/mhttp"

	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/os/gcron"
	"github.com/gogf/gf/os/glog"
)

var Register = register{
	Name:       g.Cfg().GetString("app.name"),
	Title:      g.Cfg().GetString("app.title"),
	Intro:      g.Cfg().GetString("app.intro"),
	Version:    g.Cfg().GetString("app.version"),
	Auth:       g.Cfg().GetString("app.auth"),
	Icon:       g.Cfg().GetString("app.icon"),
	Bimg:       g.Cfg().GetString("app.bimg"),
	IndexPath:  g.Cfg().GetString("app.indexPath"),
	ServerPath: g.Cfg().GetString("app.serverPath"),
}

type register struct {
	Name       string
	Title      string
	Intro      string
	Version    string
	Auth       string
	Icon       string
	Bimg       string
	IndexPath  string
	ServerPath string
}

func (rg *register) Run() {
	gcron_result := gcron.Search("app_register")
	if gcron_result == nil {
		_, err := gcron.AddOnce("*/2 * * * * ?", rg.gcronFunc, "app_register")
		if err != nil {
			g.Log().Error(err)
		}
	}
	gcron.Start("app_register")

}

func (rg *register) gcronFunc() {
	if g.Server().Status() == 1 {
		mainServerPath := g.Cfg().GetString("app.mainServerPath")
		url := mainServerPath + "/system/sysApp/register"
		params := g.Map{
			"name":        rg.Name,
			"title":       rg.Title,
			"intro":       rg.Intro,
			"version":     rg.Version,
			"auth":        rg.Auth,
			"icon":        rg.Icon,
			"bimg":        rg.Bimg,
			"index_path":  rg.IndexPath,
			"server_path": rg.ServerPath,
		}
		code, msg, data := mhttp.Client.Post(url, params)

		if code == 0 {
			g.Log().Error("主服务链接失败")
		}
		if code == -401 {
			g.Log().Error("主服务请求失败:", msg)
		}
		if code == -1 {
			g.Log().Error("注册请求失败:", msg)
		}
		if code == 200 {
			glog.Debug("[register][应用注册成功]", data.Map())
		}

	}

}
